<template>
  <HomePannel title="热门品牌" sub-title="国际经典 品质保证">
    <!-- 在home-pannel组件中 将按钮放进right插槽 -->
    <template v-slot:right>
      <a @click="toggle(-1)" :class="{ disabled: index === 0 }" href="javascript:;" class="iconfont icon-angle-left prev"></a>
      <a @click="toggle(1)" :class="{ disabled: index === 1 }" href="javascript:;" class="iconfont icon-angle-right next"></a>
    </template>
    <!-- 将商品展示的列表放进默认插槽中 -->
    <div class="box" ref="target">
      <Transition name="fade">
        <ul v-if="brands.length" class="list" :style="{ transform: `translateX(${-index * 1240}px)` }">
          <!-- 请求回来的数据有10个品牌，但是在页面上只展示了5个 -->
          <li v-for="item in brands" :key="item.id">
            <RouterLink to="/">
              <img :src="item.picture" alt="" />
            </RouterLink>
          </li>
        </ul>
        <div v-else class="skeleton">
          <XtxSkeleton class="item" v-for="i in 5" :key="i" animated bg="#e4e4e4" width="240px" height="305px" />
        </div>
      </Transition>
    </div>
  </HomePannel>
</template>

<script>
import { ref } from 'vue'
import HomePannel from './home-pannel'
import { findBrand } from '@/api/home.js'
import { useLazyData } from '@/hooks/index'
export default {
  name: 'HomeBrand',
  components: { HomePannel },
  setup() {
    // 获取品牌的数据
    // 注意：useLazyData需要的是Api函数，如果遇到传参的情况，自己写函数在函数中调用api
    const { result, target } = useLazyData(() => findBrand(10))

    // 点击上下页的逻辑,需要用index来控制style样式
    const index = ref(0)
    const toggle = (step) => {
      const newIndex = index.value + step
      if (newIndex > 1 || newIndex < 0) return
      index.value = newIndex
    }
    return { brands: result, target, toggle, index }
  }
}
</script>

<style scoped lang="less">
.home-panel {
  background: #f5f5f5;
}
.iconfont {
  width: 20px;
  height: 20px;
  background: #ccc;
  color: #fff;
  display: inline-block;
  text-align: center;
  margin-left: 5px;
  background: @xtxColor;
  &::before {
    font-size: 12px;
    position: relative;
    top: -2px;
  }
  &.disabled {
    background: #ccc;
    cursor: not-allowed;
  }
}
.box {
  display: flex;
  width: 100%;
  height: 345px;
  overflow: hidden;
  padding-bottom: 40px;
  .list {
    width: 200%;
    display: flex;
    transition: all 1s;
    li {
      margin-right: 10px;
      width: 240px;
      &:nth-child(5n) {
        margin-right: 0;
      }
      img {
        width: 240px;
        height: 305px;
      }
    }
  }
}
.skeleton {
  width: 100%;
  display: flex;
  .item {
    margin-right: 10px;
    &:nth-child(5n) {
      margin-right: 0;
    }
  }
}
</style>
